#include <unistd.h>
#include <memory>
#include <iostream>
using std::cout;
using std::endl;
using std::string;
using std::unique_ptr;
using std::shared_ptr;

//自定义删除器的方式
struct Myfpcloser
{
    void operator()(FILE * fp) 
    {
        if(fp){ 
            fclose(fp);
            cout << "fclose(fp)" << endl;
        }
    }
};

void test0()
{
    unique_ptr<FILE, Myfpcloser> up(fopen("test.txt", "a+"));
    /* unique_ptr<FILE> up(fopen("test.txt", "a+")); */
    
    string msg("this is a test\n");
    fwrite(msg.c_str(), 1, msg.size(), up.get());

    /* fclose(up.get());//关闭文件 */
}

void test1()
{
    /* shared_ptr<FILE> sp(fopen("test.txt", "a+"), Myfpcloser()); */
    Myfpcloser fp;
    shared_ptr<FILE> sp(fopen("test.txt", "a+"), fp);
    
    string msg("this is a test\n");
    fwrite(msg.c_str(), 1, msg.size(), sp.get());
}

int main()
{
    test1();
    return 0;
}

